package com.terrynoya.fight.io
{
	public class FileSystem
	{
		public static const TITLE_REGEXP:RegExp = /^\s*\[(.+?)\]\s*$/;
		public static const PARSED_LINE_REG:RegExp = /^\s*(.+?)\s*=\s*(.+?)\s*$/;
		
		public function FileSystem()
		{
			
		}
		
		public static function build(fileData:String):TextFile
		{
			var sections:Array = new Array();
			var sectionLines:Array;
			var sectionTitle:String;
			var sectionParsedLines:Array;
			
			var lines:Array = fileData.split("\r\n");
			for (var i:int = 0; i < lines.length; i++) 
			{
				var line:String = lines[i];
				var commentIndex:int = line.indexOf(";");
				var noCommLine:String = line;
				//不是以;开头
				if(commentIndex != -1)
				{
					noCommLine = line.substr(0,commentIndex);
				}
				if(noCommLine == "")
				{
					continue;
				}
				if(TITLE_REGEXP.test(noCommLine))
				{
					if(sectionTitle != null)
					{
						sections.push(new TextSection(sectionTitle,sectionLines,sectionParsedLines));
					}
					var matches:Array = noCommLine.match(TITLE_REGEXP);
					sectionLines = new Array();
					sectionTitle = matches[1];
					sectionParsedLines = new Array();
				}
				else if(sectionTitle != "")
				{
					sectionLines.push(noCommLine);
					if(PARSED_LINE_REG.test(noCommLine))
					{
						var sectionMatches:Array = noCommLine.match(PARSED_LINE_REG);
						var key:String = sectionMatches[1];
						var value:String = sectionMatches[2];
						sectionParsedLines.push(new KeyValuePair(key,value))
					}
				}
			}
			if(sectionTitle != null)
			{
				sections.push(new TextSection(sectionTitle,sectionLines,sectionParsedLines));
			}
			return new TextFile(sections);
		}
	}
}